package com.doge.walknovel.business.novel.widgets

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.drawable.toBitmap
import com.doge.wnpro.R
import com.doge.walknovel.utils.dp
import com.doge.walknovel.utils.getDrawable
import com.doge.walknovel.utils.isMainThread

class PostStarView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : View(context, attrs) {
    companion object {
        const val NONE = 0
        const val HALF = 1
        const val FILL = 2
    }

    private val paint by lazy { Paint() }
    private val light by lazy { getDrawable(R.mipmap.rate_star_light)!!.toBitmap() }
    private val grey by lazy { getDrawable(R.mipmap.rate_star_grey)!!.toBitmap() }
    private var mode: Int = NONE

    fun set(value: Int) {
        require(isMainThread())
        mode = value
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        setMeasuredDimension(36.dp, 36.dp)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas ?: return

        val percent = when (mode) {
            NONE -> 0f
            HALF -> 0.5f
            FILL -> 1f
            else -> return
        }
        val side = percent * width
        canvas.save()
        canvas.clipRect(0f, 0f, side, height.toFloat())
        canvas.drawBitmap(light, 0f, 0f, paint)
        canvas.restore()
        canvas.save()
        canvas.clipRect(side, 0f, width.toFloat(), height.toFloat())
        canvas.drawBitmap(grey, 0f, 0f, paint)
        canvas.restore()
    }
}